import { defineStore } from 'pinia'
import { showErrorMsg, showSuccessMsg } from '@/utils/alterMessage.js'
import $ajax from '@/api/to8030.js'
import router from '@/router/index.js'

export const useLoginStore = defineStore('login', {
  state: () => ({
    isLogin: false,
    ruleForm: {
      telephone: '',
      password: '',
      smsCode: ''
    },
    isSending: false,
    countdown: 0
  }),
  actions: {
    clearForm() {
      this.ruleForm.telephone = ''
      this.ruleForm.password = ''
      this.ruleForm.smsCode = ''
    },
    async sendSmsCode() {
      const tel = this.ruleForm.telephone
      if (this.countdown > 0 || this.isSending) {
        return // 防止重复点击发送
      }
      if (!tel) {
        showErrorMsg('请输入手机号')
        return
      }
      this.isSending = true
      this.startCountdown()
      // console.log('发送验证码', tel)
      // sessionStorage.setItem('token', tel)
      const path = '/member/login/code/get/' + tel
      const res = await $ajax.get(path)
      if (res != null && res.code != null && res.code === 200) {
        showSuccessMsg('验证码发送成功')
      } else {
        console.log('验证码发送失败')
        this.countdown = 0
      }
      this.isSending = false
      // 假设在这个方法中实现发送验证码的逻辑
      // 可以调用sendVerificationCode()方法发送验证码
      // 这里只是简单模拟发送过程
    },
    startCountdown() {
      this.countdown = 60
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    async loginByPwd() {
      const path = '/member/login/' + this.ruleForm.telephone
      const res = await $ajax.post(path, this.ruleForm.password)
      sessionStorage.setItem('userID', this.ruleForm.telephone)
      if (res != null && res.code != null && res.code === 200) {
        showSuccessMsg('登录成功')
        sessionStorage.setItem('currentUser', JSON.stringify(res.result))
        sessionStorage.setItem('roleId', res.result.roleId)
        sessionStorage.setItem('token', res.result.token)
        await router.push({
          path: '/home'
        })
        this.clearForm()
      } else {
        showErrorMsg('登录失败')
        this.ruleForm.password = ''
      }
    },
    async loginBySms() {
      const data = {
        memNumber: this.ruleForm.telephone,
        verifyCode: this.ruleForm.smsCode
      }
      sessionStorage.setItem('userID', this.ruleForm.telephone)
      const path = '/member/login/code'
      const res = await $ajax.post(path, data)
      if (res != null && res.code != null && res.code === 200) {
        showSuccessMsg('登录成功')
        sessionStorage.setItem('currentUser', JSON.stringify(res.result))
        sessionStorage.setItem('roleId', res.result.roleId)
        sessionStorage.setItem('token', res.result.token)
        this.clearForm()
        await router.push({
          path: '/home'
        })
      } else {
        showErrorMsg('登录失败')
        this.ruleForm.smsCode = ''
      }
    }
  }
})
